<template>
	<div>

		<el-upload list-type="picture-card" ref="upload" :file-list="upconfig.imgList" :action="upconfig.action"
			:headers="upconfig.headers" :accept="upconfig.accept" :limit="upconfig.limit" :on-change="handleChange"
			:auto-upload="false" :on-remove="handleRemove" :on-exceed="handleLimit" multiple
			:on-preview="handlePreview">
			<i class="el-icon-plus"></i>
		</el-upload>

		<el-button type="primary" @click="handleSend">上传</el-button>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>

	</div>

</template>
<script>
	import uploader from '@/utils/uploader';
	export default {
		data() {
			return {
				upconfig: {
					//文件上传相关参数
					accept: '.jpg,.jpeg,.png,.pdf,.doc,.docx',
					limit: 5,
					headers: {
						token: "fasldkfjalskdfjalsd jfkalsdfj alskdfj"
					},
					imgList: [],
					fileList: [],
					rids: [], //要删除的id
					action: ""
				},
				dialogImageUrl: '',
				dialogVisible: false,
				disabled: false
			};
		},
		methods: {
			/***********************文件上传区域开始****************/
			//文件数量超限提示
			handleLimit: function() {
				this.$message.warning("最多可上传" + this.upconfig.limit + "个文件");
			},
			handleChange: function(file, list) {
				//判断文件格式和数量
				var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
				var extarr = ['jpg', 'jpeg', 'png', "pdf"];
				var sizeok = file.size / 1024 / 1024 < 5;
				if (extarr.lastIndexOf(ext) == -1) {
					this.$message.error("上传文件格式必须为" + extarr.join(","));
					//删除刚上传的文件
					this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
					return;
				}
				if (!sizeok) {
					this.$message.error("上传文件大小最大不超过5M");
					this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
					return;
				}

				this.upconfig.fileList = list;
			},
			// 文件列表移除文件时的钩子
			handleRemove: function(file, fileList) {
				if (file.id) { //如果存储 id即为已经上传好的图片
					this.upconfig.rids.push(file.id);
				}
				this.upconfig.fileList = fileList;
			},
			handlePreview(file) {
				console.log('预览文件', file);
			},
			handleSend() {
				var fd = new FormData();
				var fid = 0;
				fd.append("token", '123123123123');
				this.upconfig.fileList.forEach(file => {
					if (file.raw) {
						fd.append("file" + fid, file.raw);
						fid++;
					}
				});

				uploader.post("test", fd).then(res => {

				}).catch(error => {});
			}
		}
	}
</script>

<style>
</style>